package com.greenDao.activity.tool.button.event;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;

import com.greenDao.activity.tool.DatabaseUtils;
import com.greenDao.activity.tool.GuiUtils;
import com.greenDao.activity.tool.LogUtils;
import com.greenDao.pojo.Event;
import com.greenDao.pojo.Movie;
import com.greenDao.pojo.PojoUtils;

public class AddEventButton implements View.OnClickListener {

	private final Activity activity;
	private final EditText nameText;
	private final Spinner spinner;
	private final EditText dateText;
	private final EditText commentText;

	public AddEventButton(Activity activity, EditText nameText, Spinner spinner, EditText dateText, EditText commentText) {
		this.activity = activity;
		this.nameText = nameText;
		this.spinner = spinner;
		this.dateText = dateText;
		this.commentText = commentText;
	}

	@Override
	public void onClick(View v) {

		String name = nameText.getText().toString();
		if (!DatabaseUtils.findEventsByName(name).isEmpty()) {
			GuiUtils.showAlertDialog(activity, "name of events should be unique");
			return;
		}

		String date = dateText.getText().toString();
		if (name.isEmpty() || date.isEmpty() || spinner.getSelectedItem() == null) {
			GuiUtils.showAlertDialog(activity, "name, date and movie are obligatory");
			return;
		}

		if (!date.matches("\\d\\d-\\d\\d-\\d\\d\\d\\d--\\d\\d\\.\\d\\d")) {
			GuiUtils.showAlertDialog(activity, "bad date syntax, try again");
			dateText.setHint("dd-MM-yyyy--HH.mm");
			return;
		}
		Date dt = null;
		try {
			dt = new SimpleDateFormat("dd-MM-yyyy--HH.mm", Locale.US).parse(date);
		} catch (ParseException e) {
			Log.e("AddEventButton onClick", "simple date format exception", e);
			GuiUtils.showAlertDialog(activity, "problem with parsing data");
			return;
		}

		String title = spinner.getSelectedItem().toString().split("-")[2];
		String comment = commentText.getText().toString();

		Movie movie = DatabaseUtils.findMoviesByTitle(title).get(0);
		Event event = PojoUtils.createEvent(name, movie, dt, comment);
		DatabaseUtils.saveEvent(event);
		LogUtils.logAllEvents(DatabaseUtils.getAllEvents());

		activity.finish();
	}
}
